class SessionsController < ApplicationController
  # creates a new session for a user
  def create
    @user = User.authenticate(params[:email], params[:password])
    if @user
      if @user.validated && !@user.isflagged  # ensure user is validated and not flagged
        session[:user_id] = @user.id
        redirect_to root_url
      else
        respond_to do |format|
          if !@user.validated # email validation notification
            format.html { redirect_to root_url, :notice => 'You have not validated your email address. Check your inbox.' }
          else @user.isflagged # user flag notification
            format.html { redirect_to root_url, :notice => 'Your account has been flagged, please contact the site admin.' }
          end
          format.json { head :ok }
        end
      end
    else
      respond_to do |format|
        format.html { redirect_to root_url, :notice => 'Invalid email or password' }
        format.json { head :ok }
      end
    end
  end

  # destroys the users session
  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end
end
